<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="通用码" prop="universalCode">
              <el-input v-model="queryParams.universalCode" placeholder="请输入通用码" clearable />
            </el-form-item>
            <el-form-item label="月份" prop="month">
              <el-input v-model="queryParams.month" placeholder="请输入月份" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['plan:restockingPlanSum:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['plan:restockingPlanSum:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['plan:restockingPlanSum:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button v-hasPermi="['plan:restockingPlanSum:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['plan:restockingPlanSum:edit']" type="success" plain icon="Edit" @click="handlePurchase"
              >未下单批量发起采购
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" @click="handleGen">批量分配供应商</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="restockingPlanSumList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="" align="center" prop="id" />
        <el-table-column label="通用码" align="center" prop="universalCode" />
        <el-table-column label="平台类型" align="center" prop="platformType" />
        <el-table-column label="月份" align="center" prop="month" />
        <!--        <el-table-column label="预计总销售数量" align="center" prop="expectedTotalSaleQuantity" />-->
        <el-table-column label="亚马逊_在途" align="center" prop="fbaOnTheWay" />
        <el-table-column label="其他在途" align="center" prop="otherOnTheWay" />
        <el-table-column label="亚马逊可售" align="center" prop="fbaSellable" />
        <el-table-column label="其他可售" align="center" prop="otherSellable" />
        <el-table-column label="海外仓库库存" align="center" prop="overseasWarehouseInventory" />
        <el-table-column label="国内仓库库存" align="center" prop="domesticWarehouseInventory" />
        <el-table-column label="供应商库存" align="center" prop="supplierInventory" />
        <el-table-column label="总库存" align="center" prop="totalInventory" />
        <el-table-column label="库存缺口" align="center" prop="inventoryShortfall" />
        <el-table-column label="安全库存预留数量" align="center" prop="reserveSafetyStockNum" />
        <el-table-column label="总需求" align="center" prop="aggregateDemand" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            {{ restocking_plan_status.find((item) => item.value === scope.row.status)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.aggregateDemand > 0" type="primary" @click="bindSupplier(scope.row)">绑定供应商</el-button>
            <!--            <el-tooltip content="修改" placement="top">-->
            <!--              <el-button v-hasPermi="['plan:restockingPlanSum:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>-->
            <!--            </el-tooltip>-->
            <!--            <el-tooltip content="删除" placement="top">-->
            <!--              <el-button-->
            <!--                v-hasPermi="['plan:restockingPlanSum:remove']"-->
            <!--                link-->
            <!--                type="primary"-->
            <!--                icon="Delete"-->
            <!--                @click="handleDelete(scope.row)"-->
            <!--              ></el-button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改下单计划汇总对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="restockingPlanSumFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="通用码" prop="universalCode">
          <el-input v-model="form.universalCode" placeholder="请输入通用码" />
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-input v-model="form.month" placeholder="请输入月份" />
        </el-form-item>
        <el-form-item label="预计总销售数量" prop="expectedTotalSaleQuantity">
          <el-input v-model="form.expectedTotalSaleQuantity" placeholder="请输入预计总销售数量" />
        </el-form-item>
        <el-form-item label="亚马逊_在途" prop="fbaOnTheWay">
          <el-input v-model="form.fbaOnTheWay" placeholder="请输入亚马逊_在途" />
        </el-form-item>
        <el-form-item label="其他在途" prop="otherOnTheWay">
          <el-input v-model="form.otherOnTheWay" placeholder="请输入其他在途" />
        </el-form-item>
        <el-form-item label="亚马逊可售" prop="fbaSellable">
          <el-input v-model="form.fbaSellable" placeholder="请输入亚马逊可售" />
        </el-form-item>
        <el-form-item label="其他可售" prop="otherSellable">
          <el-input v-model="form.otherSellable" placeholder="请输入其他可售" />
        </el-form-item>
        <el-form-item label="海外仓库库存" prop="overseasWarehouseInventory">
          <el-input v-model="form.overseasWarehouseInventory" placeholder="请输入海外仓库库存" />
        </el-form-item>
        <el-form-item label="国内仓库库存" prop="domesticWarehouseInventory">
          <el-input v-model="form.domesticWarehouseInventory" placeholder="请输入国内仓库库存" />
        </el-form-item>
        <el-form-item label="供应商库存" prop="supplierInventory">
          <el-input v-model="form.supplierInventory" placeholder="请输入供应商库存" />
        </el-form-item>
        <el-form-item label="总库存" prop="totalInventory">
          <el-input v-model="form.totalInventory" placeholder="请输入总库存" />
        </el-form-item>
        <el-form-item label="库存缺口" prop="inventoryShortfall">
          <el-input v-model="form.inventoryShortfall" placeholder="请输入库存缺口" />
        </el-form-item>
        <el-form-item label="安全库存预留数量" prop="reserveSafetyStockNum">
          <el-input v-model="form.reserveSafetyStockNum" placeholder="请输入安全库存预留数量" />
        </el-form-item>
        <el-form-item label="总需求" prop="aggregateDemand">
          <el-input v-model="form.aggregateDemand" placeholder="请输入总需求" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-dialog v-model="bindSupllierDialog.visible" :title="bindSupllierDialog.title" width="1200px" style="height: 600px" append-to-body>
    <BindSupplierView v-if="bindSupllierDialog.visible" :sum-id="sumId" />
  </el-dialog>
</template>

<script setup name="RestockingPlanSum" lang="ts">
import {
  listRestockingPlanSum,
  getRestockingPlanSum,
  delRestockingPlanSum,
  addRestockingPlanSum,
  updateRestockingPlanSum,
  sumMonthData,
  startPurchase
} from '@/api/plan/restockingPlanSum';
import { RestockingPlanSumVO, RestockingPlanSumQuery, RestockingPlanSumForm } from '@/api/plan/restockingPlanSum/types';
import BindSupplierView from '@/views/plan/restockingPlanSum/bindSupplier.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { restocking_plan_status } = toRefs<any>(proxy?.useDict('restocking_plan_status'));

const restockingPlanSumList = ref<RestockingPlanSumVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const router = useRouter();

const queryFormRef = ref<ElFormInstance>();
const restockingPlanSumFormRef = ref<ElFormInstance>();

const sumId = ref(1);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const bindSupllierDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RestockingPlanSumForm = {
  id: undefined,
  universalCode: undefined,
  platformType: undefined,
  month: undefined,
  expectedTotalSaleQuantity: undefined,
  fbaOnTheWay: undefined,
  otherOnTheWay: undefined,
  fbaSellable: undefined,
  otherSellable: undefined,
  overseasWarehouseInventory: undefined,
  domesticWarehouseInventory: undefined,
  supplierInventory: undefined,
  totalInventory: undefined,
  inventoryShortfall: undefined,
  reserveSafetyStockNum: undefined,
  aggregateDemand: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<RestockingPlanSumForm, RestockingPlanSumQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    universalCode: undefined,
    platformType: undefined,
    month: undefined,
    expectedTotalSaleQuantity: undefined,
    fbaOnTheWay: undefined,
    otherOnTheWay: undefined,
    fbaSellable: undefined,
    otherSellable: undefined,
    overseasWarehouseInventory: undefined,
    domesticWarehouseInventory: undefined,
    supplierInventory: undefined,
    totalInventory: undefined,
    inventoryShortfall: undefined,
    reserveSafetyStockNum: undefined,
    aggregateDemand: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    universalCode: [{ required: true, message: '通用码不能为空', trigger: 'blur' }],
    platformType: [{ required: true, message: '平台类型不能为空', trigger: 'change' }],
    month: [{ required: true, message: '月份不能为空', trigger: 'blur' }],
    expectedTotalSaleQuantity: [{ required: true, message: '预计总销售数量不能为空', trigger: 'blur' }],
    fbaOnTheWay: [{ required: true, message: '亚马逊_在途不能为空', trigger: 'blur' }],
    otherOnTheWay: [{ required: true, message: '其他在途不能为空', trigger: 'blur' }],
    fbaSellable: [{ required: true, message: '亚马逊可售不能为空', trigger: 'blur' }],
    otherSellable: [{ required: true, message: '其他可售不能为空', trigger: 'blur' }],
    overseasWarehouseInventory: [{ required: true, message: '海外仓库库存不能为空', trigger: 'blur' }],
    domesticWarehouseInventory: [{ required: true, message: '国内仓库库存不能为空', trigger: 'blur' }],
    supplierInventory: [{ required: true, message: '供应商库存不能为空', trigger: 'blur' }],
    totalInventory: [{ required: true, message: '总库存不能为空', trigger: 'blur' }],
    inventoryShortfall: [{ required: true, message: '库存缺口不能为空', trigger: 'blur' }],
    reserveSafetyStockNum: [{ required: true, message: '安全库存预留数量不能为空', trigger: 'blur' }],
    aggregateDemand: [{ required: true, message: '总需求不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询下单计划汇总列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRestockingPlanSum(queryParams.value);
  restockingPlanSumList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  restockingPlanSumFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RestockingPlanSumVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加下单计划汇总';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RestockingPlanSumVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getRestockingPlanSum(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改下单计划汇总';
};

/** 提交按钮 */
const submitForm = () => {
  restockingPlanSumFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRestockingPlanSum(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRestockingPlanSum(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RestockingPlanSumVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除下单计划汇总编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delRestockingPlanSum(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'plan/restockingPlanSum/export',
    {
      ...queryParams.value
    },
    `restockingPlanSum_${new Date().getTime()}.xlsx`
  );
};

/** 生成按钮操作 */
const handleGen = async () => {
  if (!queryParams.value.month) {
    proxy?.$modal.msgError('请选择月份');
    return;
  }
  loading.value = true;
  await proxy?.$modal.confirm('是否确认？').finally(() => (loading.value = false));
  loading.value = true;
  await sumMonthData(queryParams.value).finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('生成成功');
  await getList();
};

const handlePurchase = async () => {
  loading.value = true;
  await proxy?.$modal.confirm('是否确认？').finally(() => (loading.value = false));
  loading.value = true;
  await startPurchase().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/**
 * 打开运营计划
 */
const bindSupplier = (row?: RestockingPlanSumVO) => {
  // 打开一个新的页签
  // router.push({ path: '/restockingPlanSum/bindSupplier/index/' + row.id });
  bindSupllierDialog.visible = true;
  sumId.value = row.id;
};

onMounted(() => {
  getList();
});
</script>
